#!/usr/bin/env python
import numpy as np
import os, serial,time,socket,sys,json
from meas_data import meas_data
# import the server implementation

sensor="bme280"
pathname = os.path.dirname(sys.argv[0])
abspath=os.path.abspath(pathname)

idfile=abspath+"/id.json"
id_conf=0
try:
	idf=open(idfile,"r")
	id_conf=json.load(idf)['id']
	idf.close()
except:
	id_conf=0

configfile=abspath+"/config.json"
try:
	cf=open(configfile,"r")
except:
	cf=open(configfile+".template","r")

log_conf=json.load(cf)
cf.close()

parameter={"device":socket.gethostname(),"deviceid":"FF","mean_count":5,"ring_length":10,"wait":0.5,"cycle":10,"check_last":15,"check_last_shrinking":0.9,"gpg_keyid":"","digits":3,"store_dir":"/home/pi/log/","multiplicator":1000,"sensor":"BME280","sigma":3}
for n in parameter:
  if n in log_conf:
    parameter[n]=log_conf[n]

bmqtt=False
if "mqtt" in log_conf:
  bmqtt=True
  lcmq=log_conf['mqtt']
  mbroker=""
  if 'broker' in lcmq:
    mbroker=lcmq['broker']
  else:
    bmqtt=False
  mport=1883
  if 'port' in lcmq:
    mport=lcmq['port']  

# config of bme280 sensor
# use pip install RPi.bme280 for library
meas_types=["temperature","humidity","pressure"]
bbme=False
if sensor in log_conf:
  bbme=True
  if "enable" in log_conf[sensor]:
    if log_conf[sensor]['enable'] == 0:
      bbme=False
  if bbme:
    import smbus2
    import bme280
    if "port" in log_conf[sensor]:
      bme_port=log_conf[sensor]['port']
    else:
      bme_port=1
    if "address" in log_conf[sensor]:
      parameter["i2c"]=int(log_conf[sensor]['address'],16)
    else:
      parameter["i2c"]=0x77
    try:
      bme_bus=smbus2.SMBus(bme_port)
    except:
      bbme=False
    else:
      calibration_params=bme280.load_calibration_params(bme_bus,parameter["i2c"])
      bme_sigma=3
      for n in parameter:
        if n in log_conf[sensor]:
          parameter[n]=log_conf[sensor][n]
      if "sigma" in log_conf[sensor]:
        parameter["sigma"]=int(log_conf[sensor]['sigma'])
        if parameter["sigma"] < 1:
          parameter["sigma"]=1
      bme_cycle=5
      if "cycle" in log_conf[sensor]:
        bme_cycle=int(log_conf[sensor]['cycle'])
      partemp=parameter
      partemp["var_name"]="temperature"
      bme_temp=meas_data(partemp)
      parhum=parameter
      parhum["var_name"]="humidity"
      bme_hum=meas_data(parhum)
      parpress=parameter
      parpress["var_name"]="pressure"
      bme_press=meas_data(parpress)
      if ("mqtt" in log_conf[sensor]) and bmqtt:
        bme_temp.set_mqtt(broker=mbroker,port=mport)
        bme_hum.set_mqtt(broker=mbroker,port=mport)
        bme_press.set_mqtt(broker=mbroker,port=mport)
      if "sqlserver" in log_conf:
        hostname="localhost"
#        if "host" in log_conf['sqlserver']:
#	      hostname=log_conf['sqlserver']['host']
        port=8080
#        if "port" in log_conf['sqlserver']:
#	      port=int(log_conf['sqlserver']['port'])
        bme_temp.set_sql(host=hostname,port=port)
        bme_hum.set_sql(host=hostname,port=port)
        bme_press.set_sql(host=hostname,port=port)
      if "opensensemap" in log_conf[sensor]:
        osm=log_conf[sensor]['opensensemap']
        if "sensebox_id" in osm:
          sid=osm['sensebox_id']
          if "sensors" in osm:
            if "temperature" in osm['sensors']:
              bme_temp.set_sensebox(sid,osm['sensors']['temperature'])
            if "humidity" in osm['sensors']:
              bme_hum.set_sensebox(sid,osm['sensors']['humidity'])
            if "pressure" in osm['sensors']:
              bme_press.set_sensebox(sid,osm['sensors']['pressure'])


if bbme:
  while True:
  
  # read bme280 (temperature, humidity, pressure)
    bme_data=bme280.sample(bme_bus,parameter["i2c"],calibration_params)
    bme_temp.append(bme_data.temperature)
    bme_hum.append(bme_data.humidity)
    bme_press.append(bme_data.pressure)
    time.sleep(parameter['wait'])


# close the client
print("done")


